package com.qianchang.microfinance.view.mine.loan;

import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.HtmlUtil;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.element.DButton;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.AgreementBean;
import com.qianchang.microfinance.bean.HSUploadFileBean;
import com.qianchang.microfinance.bean.LoanProgBean;
import com.qianchang.microfinance.bean.LoanType;
import com.qianchang.microfinance.bean.ProjectStatus;
import com.qianchang.microfinance.bean.SubmitLoanBean;
import com.qianchang.microfinance.bean.UploadFileBean;
import com.qianchang.microfinance.bean.UserLoginInfo;
import com.qianchang.microfinance.bean.event.AgreementEvent;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.tsign.esign.tsignsdk2.TESeal;
import cn.tsign.esign.tsignsdk2.custom.Custom;
import cn.tsign.esign.tsignsdk2.custom.DialogCustom;
import cn.tsign.esign.tsignsdk2.enums.EnumTipMsgGravity;
import cn.tsign.esign.tsignsdk2.enums.EnumWindow;
import cn.tsign.esign.tsignsdk2.util.extend.Callback;
import cn.tsign.network.enums.EnumHandSignColor;

/**
 * 确认合同  贷后合同详情
 */
public class ConfirmAgreementActivity extends BaseActivity {
    private static final String TAG = "ConfirmAgreement";

    @BindView(R.id.web_view)
    WebView webView;
    @BindView(R.id.btn_submit)
    DButton btnSubmit;
    private String projectId;
    private int projectType;

    private String accountId;
    private String applyAmount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_agreement);
        ButterKnife.bind(this);
        setTitleName(getString(R.string.Label_sure_agreement));
        initData();
        setCustomStyle();
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();
        if (null != bundle) {
            projectId = bundle.getString(ConstantAppInfo.PROJECT_ID);
            projectType = bundle.getInt(ConstantAppInfo.PROJECT_TYPE);
            applyAmount = bundle.getString(SubmitLoanBean.LOAN_AMOUNT);
        }
        getAgreementInfo();

    }


    private void getAgreementInfo() {
        show();
        HttpParams params = new HttpParams();
        params.put("projectId", projectId);
        params.put("productType", projectType);
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.FIND_CONFIRM_AGREEMENT, params, new RequestCallBack<AgreementBean>() {
            @Override
            public void onSuccess(JsonResult<AgreementBean> response) {
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    initAgreement(response.getObject());
                    getSignAccountId();
                } else {
                    dismiss();
                    ToastUtil.getInstant().show(ConfirmAgreementActivity.this, response.getDescription());
                }
            }


            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ConfirmAgreementActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }
        });
    }


    private void getSignAccountId() {

        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();
        HttpParams params = new HttpParams();
        params.put("userId",usid);

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.ES_CREATEAGREE, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    DMLog.e(TAG, "onSuccess: " + response.getObject());
                    accountId = response.getObject();
//                    try {
//                        JSONObject jsonData = new JSONObject(response.getObject());
//                        if (jsonData.has("accountId")) {
//                            accountId = jsonData.getString("accountId");
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
                } else {
                    ToastUtil.getInstant().show(ConfirmAgreementActivity.this, response.getDescription());
                }
            }


            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ConfirmAgreementActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }
        });
    }


    /**
     * 显示协议
     */
    private void initAgreement(AgreementBean bean) {
        if (bean == null) return;
        WebSettings webSettings = webView.getSettings();
        webSettings.setUseWideViewPort(true);//设置此属性，可任意比例缩放
//        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setSupportZoom(false);//支持缩放
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);  //这句话将图片缩放至屏幕宽度，非常好嘛
        //加载第三方页面时，我们没办法控制别人使用http还是https，如果我们服务器和对方使用不同的协议，就需要做这个处理了。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        // 加载需要显示的网页
//        webView.addJavascriptInterface(new JavascriptInterface(), "classNameBeExposedInJs");
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        HtmlUtil htmlUtil = new HtmlUtil();
        htmlUtil.init(DMConstant.Config.BASE_URL);
        htmlUtil.getHead().append("<link rel='stylesheet' href='file:///android_asset/css/protocol.css' type='text/css'/>");
        htmlUtil.setBody(new StringBuilder(bean.getAgreementText()));
        webView.loadDataWithBaseURL("", htmlUtil.createHtml(), "text/html", "utf-8", "");
    }

    // 对SDK里的页面做一些样式设置
    private void setCustomStyle() {
        //对SDK做个性化设置
        Custom custom = new Custom();
        //设置标题的背景颜色
        custom.setTitleBackgroundColor(R.color.black);
        //设置标题的文字颜色
        custom.setTitleTextColor(R.color.red);
        //设置标题文本
        custom.setTitleText(R.string.Label_sure_agreement);
        //设置手绘签名前的提示语
        custom.setTipMsg("请签名");
        //设置提示语对齐方向
        custom.setTipMsgGravity(EnumTipMsgGravity.center);
        //设置手绘的签署提供的颜色,只能是红,黑,蓝
        custom.getHandColor().add(EnumHandSignColor.Blue);
        custom.getHandColor().add(EnumHandSignColor.Black);
        custom.getHandColor().add(EnumHandSignColor.Red);

        //快捷签弹出式对话框的样式
        DialogCustom dialogCustom = new DialogCustom();
        dialogCustom.setCancelResourceId(R.drawable.tsign_quick_sign_dialog_cancel);
        dialogCustom.setFullScreenResourceId(R.drawable.tsign_quick_sign_dialog_full_screen);
        dialogCustom.setClearResourceId(R.drawable.tsign_quick_sign_dialog_clear);
        dialogCustom.setConfirmResourceId(R.drawable.tsign_quick_sign_dialog_confirm);
        custom.setDialogCustom(dialogCustom);

        TESeal.getInstance().setmCustom(custom);
    }


    @OnClick(R.id.btn_submit)
    public void onViewClicked() {
        checkAgreement();

    }

    /**
     * 确认合同
     */
    private void checkAgreement() {
        TESeal.getInstance().quickToSign(ConfirmAgreementActivity.this, accountId, EnumWindow.Dialog, new Callback() {

            @Override
            public void didSignBackImage(String id, String sealImagePath) {
//                uploadFile(sealImagePath);        //2018.1.24 鸿盛科技注释迪蒙代码

                hsuploadFile(sealImagePath);        //2018.1.24 新增自己的签名上传图片

            }

            @Override
            public void onError(JSONObject json) {
                ToastUtil.getInstant().show(ConfirmAgreementActivity.this, json.toString());
            }

            @Override
            public void onCancel(JSONObject json) {
                ToastUtil.getInstant().show(ConfirmAgreementActivity.this, json.toString());
            }
        });
    }

    public void confirm(String fileId) {

        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();
        HttpParams params = new HttpParams();
        params.put("projectId", projectId);
        params.put("userType", "");
        params.put("method", "confirm");
        params.put("status", "5");
//        params.put("fileId", fileId);
        params.put("amount",applyAmount);
        params.put("userId",usid);

        show();
        DMOKHttpUtils.getInstance().post(this, DMConstant.Config.BASE_USER + "/project/" + LoanType.getNameByType(String.valueOf(projectType)) + DMConstant.Config.V + "/confirm.do", params, new RequestCallBack<LoanProgBean>() {
            @Override
            public void onSuccess(JsonResult<LoanProgBean> response) {
                dismiss();
                setResult(-1);      //设置从确认借款点击跳转合同过来回调回去页面判断结束页面
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    if (LoanType.JBD.equals(String.valueOf(projectType))) {

                        /*** 2018.1.24 注释掉迪蒙代码
                        Bundle bundle = getBundle();
                        bundle.putString(ConstantAppInfo.PROJECT_STATUS, ProjectStatus.DFK);
                        startActivity(LoanProgressActivity.class, bundle);
                         ****/


//                        startActivity(HSLoanWithdrawActivity.class, true);          //鸿胜科技新增自己代码
                        LoanProgBean loanProgBean = response.getObject();
                        if(loanProgBean != null){
                            String bidId = loanProgBean.getBidId();
                            String biadid = loanProgBean.getBiaodiId();
                            String userId = loanProgBean.getUserId();
                            Bundle bundle = new Bundle();
                            bundle.putString("userId",userId);
                            bundle.putString("bidId",biadid);
                            startActivity(HSLoanWithdrawActivity.class,bundle,true);
                        }else {
                            ToastUtil.getInstant().show(getApplicationContext(), "申请失败");
                        }

                    } else {
                        ToastUtil.getInstant().show(ConfirmAgreementActivity.this, "申请成功");
                    }
                    EventBus.getDefault().post(new AgreementEvent(true));
                    finish();
                } else {
                    ToastUtil.getInstant().show(ConfirmAgreementActivity.this, response.getDescription());
                }

                ConfirmAgreementActivity.this.finish();
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ConfirmAgreementActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }
        });
    }


    /**
     * 只有单个文件才支持上传
     *
     * @param imagePath 文件路径
     */
    public void uploadFile(final String imagePath) {
        if (null == imagePath) {
            return;
        }
        File file = new File(imagePath);
        Map<String, File> files = new HashMap<>();
        files.put(file.getName(), file);
        Map<String, String> fileParamsMap = new HashMap<>();
        fileParamsMap.put("allowFile", "jpg,png");
        fileParamsMap.put("fileType", "0");
        fileParamsMap.put("isTransform", "false");
        show();
        DMOKHttpUtils.getInstance().uploadFile(this, DMConstant.ApiURL.UPLOAD_FILE, fileParamsMap, "uploadFile", files, new RequestCallBack<ArrayList<UploadFileBean>>() {

            @Override
            public void onSuccess(JsonResult<ArrayList<UploadFileBean>> response) {
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    ArrayList<UploadFileBean> uploadFileList = response.getObject();
                    if (null != uploadFileList && uploadFileList.size() > 0) {
                        confirm(uploadFileList.get(0).getId());
                    } else {
                        dismiss();
                        ToastUtil.getInstant().show(ConfirmAgreementActivity.this.getApplicationContext(), getString(R.string.upload_failed));
                    }
                } else {
                    dismiss();
                    ToastUtil.getInstant().show(ConfirmAgreementActivity.this.getApplicationContext(), response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ConfirmAgreementActivity.this.getApplicationContext(), msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }



    /**
     * 只有单个文件才支持上传
     * @param imagePath 文件路径
     */
    public void hsuploadFile(final String imagePath) {
        if (null == imagePath) {
            return;
        }

        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();

        File file = new File(imagePath);
        Map<String, File> files = new HashMap<>();
        files.put(file.getName(), file);
        Map<String, String> fileParamsMap = new HashMap<>();
        fileParamsMap.put("allowFile", "jpg,png");
        fileParamsMap.put("fileType", "0");
        fileParamsMap.put("isTransform", "false");
        fileParamsMap.put("userId",usid);
        fileParamsMap.put("projectId",projectId);

        show();
        DMOKHttpUtils.getInstance().uploadFile(this, DMConstant.ApiURL.WFILE_UPLOAD, fileParamsMap, "uploadFile", files, new RequestCallBack<HSUploadFileBean>() {

            @Override
            public void onSuccess(JsonResult<HSUploadFileBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    HSUploadFileBean uploadFileBean = response.getObject();
                    confirm("");

//                    if (null != uploadFileBean ) {
//                        confirm(uploadFileBean.getId());
//                    } else {
//                        ToastUtil.getInstant().show(getApplicationContext(), getString(R.string.upload_failed));
//                    }
                } else {
                    dismiss();
                    ToastUtil.getInstant().show(getApplicationContext(), response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(getApplicationContext(), msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }



}







//        交易密码
//        show();
//        HttpParams params = new HttpParams();
//        DMOKHttpUtils.getInstance().post(getApplicationContext(), DMConstant.ApiURL.FIND_TRAD_PWD, params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(JsonResult<String> response) {
//                dismiss();
//                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
//                    String info = response.getObject();//0 表示已有支付密码、1 表示没有支付密码
//                    if ("0".equals(info)) {
//                        checkAgreement();
//                    } else {
//                        DimengConfirmAlertDialog confirmAlertDialog = DimengConfirmAlertDialog.newInstance("", "请先设置支付密码");
//                        confirmAlertDialog.setOnDialogClickListener(new DimengConfirmAlertDialog.OnDialogClickListener() {
//                            @Override
//                            public void agree() {
//                                startActivity(SettingTradPasswordActivity.class);
//                            }
//
//                            @Override
//                            public void cancel() {
//
//                            }
//                        });
//                        confirmAlertDialog.show(getSupportFragmentManager(), getClass().getSimpleName());
//                    }
//                }
//            }
//            @Override
//            public void onFailure(String msg) {
//                dismiss();
//                ToastUtil.getInstant().show(ConfirmAgreementActivity.this, msg);
//            }
//
//            @Override
//            public void onConnectFailure(String msg) {
//            }
//        });

//    private void showTradPwdDialog() {
//        InputPwdDialog inputDialog = new InputPwdDialog(ConfirmAgreementActivity.this);
//        inputDialog.setForgetPwdListener(new InputPwdDialog.ForgetPwdListener() {
//            @Override
//            public void forgetPwd() {
//                Intent intent = new Intent(ConfirmAgreementActivity.this, ForgetActivityOne.class);
//                intent.putExtra(SettingTradPasswordActivity.IS_TRAD_PWD, true);
//                startActivity(intent);
//            }
//        });
//        inputDialog.setOnInputFinishListener(new InputPwdDialog.OnInputFinishListener() {
//            @Override
//            public void finish(String password) {
//                checkAgreement();//支付密码  要加密
//            }
//        });
//        inputDialog.show();
//    }
